import request from '@/config/axios'

// 打卡图片/视频记录类型（前端使用）
export interface CheckInImageVO {
  id: number
  url: string
  type: 'image' | 'video'
  status: 'pending' | 'approved' | 'rejected'
  comment?: string
  reviewTime?: string
}

// 按天分组的打卡记录类型（前端使用）
export interface DailyCheckInRecordVO {
  date: string // 日期，格式：YYYY-MM-DD
  images: CheckInImageVO[]
  allApproved: boolean
}

// 打卡记录类型（前端使用）
export interface CheckInRecordVO {
  id: number
  date: string
  uploadTime?: string
  images: CheckInImageVO[]
  dailyRecords?: DailyCheckInRecordVO[] // 按天分组的记录，仅type=2时使用
  allApproved: boolean
}

// 后端返回的打卡记录类型
export interface RefundActivityPunchDO {
  id: number
  userId: number
  activityRecordId: number
  dayNumber?: number // 改为可选，因为活动健康报告审核没有天数概念
  punchUrl?: string
  checkStatus: number // 0-待审核 1-已通过 2-已拒绝
  advice?: string
  type: number // 1-活动健康报告审核 2-打卡记录审核等，根据stage来区分
  createTime: number
  updateTime: number
  creator?: string
  updater?: string
  deleted: boolean
}

// 后端返回的退款活动记录数据类型
export interface RefundActivityRecordRespVO {
  id: number
  userId: number
  mobile: string
  nickname: string
  activityId: number
  activityName?: string
  productName: string
  spuId: number
  skuId: number
  stage: number
  punchCardRule?: number
  activityUploadProof?: boolean
  hasClosed?: boolean // 打卡是否已终止
  closeReason?: string // 终止原因
  refundActivityPunchList: RefundActivityPunchDO[]
  createTime: number
  isAfterSale?: boolean
  orderId?: number
  afterSaleId?: number
  transMap?: Record<string, any>
}

// 前端使用的退款活动记录类型（转换后）
export interface RefundActivityRecordVO {
  id: number
  userId: number
  userName: string
  userAccount: string
  mobile: string
  nickname: string
  activityId: number
  activityName: string
  productName: string
  spuId: number
  skuId: number
  stage: number
  punchCardRule: number
  activityUploadProof: boolean
  hasClosed?: boolean // 打卡是否已终止
  closeReason?: string // 终止原因
  beforeImage?: string
  afterImage?: string
  checkInRecords: CheckInRecordVO[]
  status: number // 0-进行中 1-已完成 2-已退款
  createTime: string
  isAfterSale?: boolean
  orderId?: number
  afterSaleId?: number
  transMap?: Record<string, any>
}

// 分页查询参数
export interface RefundActivityRecordPageReqVO extends PageParam {
  userId?: number
  mobile?: string
  createTime?: string[]
}

// 审核请求类型（根据OpenAPI文档更新）
export interface ReviewRequestVO {
  id: number // 打卡记录的编号 (required)
  checkStatus: number // 审核状态：0-待审核 1-审核通过 2-审核不通过 (required)
  advice?: string // 建议 (optional)
}

// 结束退款活动记录请求类型
export interface RefundActivityRecordCloseReqVO {
  id: number // 退款活动记录编号 (required)
  hasClosed: boolean // 是否结束活动 (required)
  closeReason?: string // 结束原因 (optional)
}

// 审核接口返回类型（根据OpenAPI文档）
export interface CommonResultBoolean {
  code: number
  data: boolean
  msg: string
}

// 判断媒体类型的工具函数
const getMediaType = (url: string): 'image' | 'video' => {
  if (!url) return 'image'
  
  const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv', '.m4v']
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']
  
  const urlLower = url.toLowerCase()
  
  // 检查视频扩展名
  if (videoExtensions.some(ext => urlLower.includes(ext))) {
    return 'video'
  }
  
  // 检查图片扩展名
  if (imageExtensions.some(ext => urlLower.includes(ext))) {
    return 'image'
  }
  
  // 默认返回图片类型
  return 'image'
}

// 数据转换函数：将后端数据转换为前端期望的格式
export const transformRefundActivityRecord = (data: RefundActivityRecordRespVO): RefundActivityRecordVO => {
  // 根据新的阶段性机制转换数据
  let checkInRecords: CheckInRecordVO[] = []
  
  if (data.refundActivityPunchList && data.refundActivityPunchList.length > 0) {
    // 根据type分组处理不同类型的审核记录
    const recordsByType = data.refundActivityPunchList.reduce((acc, punch) => {
      const typeKey = punch.type
      if (!acc[typeKey]) {
        acc[typeKey] = []
      }
      acc[typeKey].push(punch)
      return acc
    }, {} as Record<number, RefundActivityPunchDO[]>)

    // 转换为前端期望的格式
    checkInRecords = Object.entries(recordsByType).map(([type, punches]) => {
      const typeNum = parseInt(type)
      
      // 获取阶段名称
      const getStageName = (type: number, stage: number) => {
        if (type === 1) {
          return '活动健康报告审核'
        } else if (type === 2) {
          return '打卡记录审核'
        } else {
          return `第${type}阶段审核`
        }
      }
      
      const images: CheckInImageVO[] = punches
        .filter(punch => punch.punchUrl) // 只包含有资料URL的记录
        .map(punch => {
          const mediaType = getMediaType(punch.punchUrl!)
          console.log(`URL: ${punch.punchUrl}, 检测到的媒体类型: ${mediaType}`)
          
          return {
            id: punch.id,
            url: punch.punchUrl!,
            type: mediaType, // 根据URL正确判断媒体类型
            status: punch.checkStatus === 1 ? 'approved' : punch.checkStatus === 2 ? 'rejected' : 'pending',
            comment: punch.advice,
            reviewTime: punch.updateTime ? new Date(punch.updateTime).toLocaleString() : undefined
          }
        })

      const allApproved = images.length > 0 && images.every(img => img.status === 'approved')

      // 如果是打卡记录审核（type=2），按天分组
      let dailyRecords: DailyCheckInRecordVO[] | undefined = undefined
      if (typeNum === 2 && images.length > 0) {
        // 按天分组
        const recordsByDate = images.reduce((acc, image) => {
          // 根据图片对应的punch记录的createTime获取日期
          const punch = punches.find(p => p.id === image.id)
          if (punch) {
            const date = new Date(punch.createTime).toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            }).replace(/\//g, '-') // 格式化为 YYYY-MM-DD
            
            if (!acc[date]) {
              acc[date] = []
            }
            acc[date].push(image)
          }
          return acc
        }, {} as Record<string, CheckInImageVO[]>)

        // 转换为数组并排序
        dailyRecords = Object.entries(recordsByDate)
          .map(([date, dailyImages]) => ({
            date,
            images: dailyImages,
            allApproved: dailyImages.every(img => img.status === 'approved')
          }))
          .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()) // 按日期升序排序
      }

      return {
        id: typeNum,
        date: getStageName(typeNum, data.stage),
        uploadTime: punches[0]?.createTime ? new Date(punches[0].createTime).toLocaleString() : undefined,
        images,
        dailyRecords,
        allApproved
      }
    }).sort((a, b) => a.id - b.id) // 按类型排序
  }

  return {
    id: data.id,
    userId: data.userId,
    userName: data.nickname || '未知用户',
    userAccount: data.mobile || '',
    mobile: data.mobile,
    nickname: data.nickname,
    activityId: data.activityId,
    activityName: data.activityName || '未知活动',
    productName: data.productName,
    spuId: data.spuId,
    skuId: data.skuId,
    stage: data.stage,
    punchCardRule: data.punchCardRule || 1,
    activityUploadProof: data.activityUploadProof || false,
    hasClosed: data.hasClosed, // 打卡是否已终止
    closeReason: data.closeReason, // 终止原因
    beforeImage: undefined, // 后端暂无此字段
    afterImage: undefined, // 后端暂无此字段
    checkInRecords,
    status: data.stage, // 使用 stage 作为 status
    createTime: new Date(data.createTime).toLocaleString(),
    isAfterSale: data.isAfterSale,
    orderId: data.orderId,
    afterSaleId: data.afterSaleId,
    transMap: data.transMap
  }
}

// 获取退款活动记录分页
export const getRefundActivityRecordPage = (params: RefundActivityRecordPageReqVO) => {
  return request.get<{
    list: RefundActivityRecordRespVO[]
    total: number
  }>({ url: '/promotion/refund-activity-record/page', params })
}

// 获取退款活动记录详情
export const getRefundActivityRecord = async (id: number): Promise<RefundActivityRecordVO> => {
  const response = await request.get<RefundActivityRecordRespVO>({ 
    url: `/promotion/refund-activity-record/get?id=${id}` 
  })
  
  // 调试：打印接口返回的原始数据
  console.log('接口返回的原始数据:', response)
  
  const transformedData = transformRefundActivityRecord(response)
  
  // 调试：打印转换后的数据
  console.log('转换后的数据:', transformedData)
  
  return transformedData
}

// 获取退款活动记录详情（直接返回原始数据，不转换）
export const getRefundActivityRecordRaw = (id: number) => {
  return request.get<RefundActivityRecordRespVO>({ 
    url: `/promotion/refund-activity-record/get?id=${id}` 
  })
}

// 审核退款活动打卡记录（根据OpenAPI文档更新）
export const reviewCheckInImage = (data: ReviewRequestVO): Promise<CommonResultBoolean> => {
  console.log('审核请求参数:', data)
  return request.put<CommonResultBoolean>({ 
    url: '/promotion/refund-activity-record/check', 
    data 
  })
}

// 执行退款
export const executeRefund = (id: number) => {
  return request.post({ url: `/promotion/refund-activity-record/refund?id=${id}` })
}

// 结束退款活动记录
export const closeRefundActivityRecord = (data: RefundActivityRecordCloseReqVO): Promise<CommonResultBoolean> => {
  console.log('结束活动请求参数:', data)
  return request.put<CommonResultBoolean>({ 
    url: '/promotion/refund-activity-record/close', 
    data 
  })
}
